// 全局变量
let inspectionTable;
let editingId = null;
let token = '';
let header = '';

// 页面加载完成后执行
$(document).ready(function() {
    // 获取CSRF令牌
    token = $("meta[name='_csrf']").attr("content");
    header = $("meta[name='_csrf_header']").attr("content");
    
    // 添加CSRF令牌到所有AJAX请求
    $.ajaxSetup({
        beforeSend: function(xhr) {
            xhr.setRequestHeader(header, token);
        }
    });

    // 初始化DataTable
    inspectionTable = $('#inspectionTable').DataTable({
        "processing": true,
        "serverSide": false,
        "ajax": {
            "url": "/security/inspection/list",
            "type": "GET",
            "dataSrc": function(json) {
                if (json.code === 200 && json.data) {
                    return json.data;
                }
                return [];
            }
        },
        "columns": [
            {"data": "inspectionId"},
            {"data": "inspectionCode"},
            {"data": "inspectionArea"},
            {"data": "inspector"},
            {"data": "inspectionTime"},
            {
                "data": "inspectionType",
                "render": function(data) {
                    switch (data) {
                        case "1": return "日常巡检";
                        case "2": return "安全巡检";
                        case "3": return "专项巡检";
                        default: return "未知";
                    }
                }
            },
            {
                "data": "inspectionResult",
                "render": function(data) {
                    return data === "0" ? 
                        '<span class="badge badge-success">正常</span>' : 
                        '<span class="badge badge-danger">异常</span>';
                }
            },
            {
                "data": "status",
                "render": function(data, type, row) {
                    if (row.inspectionResult === "0") {
                        return '<span class="badge badge-success">正常</span>';
                    }
                    
                    switch (data) {
                        case "0": return '<span class="badge badge-danger">待处理</span>';
                        case "1": return '<span class="badge badge-warning">处理中</span>';
                        case "2": return '<span class="badge badge-info">已处理</span>';
                        default: return "未知";
                    }
                }
            },
            {
                "data": null,
                "render": function(data) {
                    return '<div class="btn-group" role="group">' +
                        '<button type="button" class="btn btn-sm btn-info action-btn" onclick="viewInspection(' + data.inspectionId + ')">' +
                        '<i class="fas fa-eye"></i></button>' +
                        '<button type="button" class="btn btn-sm btn-primary action-btn" onclick="editInspection(' + data.inspectionId + ')">' +
                        '<i class="fas fa-edit"></i></button>' +
                        '<button type="button" class="btn btn-sm btn-danger action-btn" onclick="showDeleteModal(' + data.inspectionId + ')">' +
                        '<i class="fas fa-trash-alt"></i></button>' +
                        '</div>';
                }
            }
        ],
        "language": {
            "url": "https://cdn.datatables.net/plug-ins/1.10.21/i18n/Chinese.json"
        },
        "responsive": true,
        "lengthChange": true,
        "autoWidth": false,
        "searching": false,
        "paging": true,
        "info": true,
        "order": [[0, 'desc']],
        "initComplete": function() {
            loadStats();
        }
    });

    // 巡检结果变更事件
    $('#inspectionResult').change(function() {
        if ($(this).val() === "1") {
            $('#problemSection').show();
            $('#problemDesc').prop('required', true);
            $('#status').prop('required', true);
        } else {
            $('#problemSection').hide();
            $('#problemDesc').prop('required', false);
            $('#status').prop('required', false);
        }
    });
    
    // 模态框关闭时重置状态
    $('#inspectionModal').on('hidden.bs.modal', function () {
        $('#inspectionForm')[0].reset();
        $('#inspectionForm input, #inspectionForm select, #inspectionForm textarea').prop('disabled', false);
        $('.modal-footer .btn-primary').show();
        $('.modal-footer .btn-secondary').text('取消');
    });
});

// 加载安全统计数据
function loadStats() {
    $.ajax({
        url: '/security/inspection/stats',
        type: 'GET',
        success: function(res) {
            if (res.code === 200 && res.data) {
                $('#totalCount').text(res.data.totalCount || 0);
                $('#abnormalCount').text(res.data.abnormalCount || 0);
                $('#pendingCount').text(res.data.pendingCount || 0);
                
                // 更新安全指数并设置样式
                const safetyIndex = res.data.safetyIndex || 0;
                $('#safetyIndex').text(safetyIndex.toFixed(2));
                
                if (safetyIndex >= 90) {
                    $('#safetyIndex').removeClass().addClass('safety-index safety-index-high');
                } else if (safetyIndex >= 70) {
                    $('#safetyIndex').removeClass().addClass('safety-index safety-index-medium');
                } else {
                    $('#safetyIndex').removeClass().addClass('safety-index safety-index-low');
                }
            }
        }
    });
}

// 添加巡检
function addInspection() {
    editingId = null;
    $('#inspectionModalLabel').text('新增巡检');
    $('#inspectionForm')[0].reset();
    $('#inspectionId').val('');
    $('#inspectionCode').val(''); // 将由后台生成
    $('#inspectionTime').val(new Date().toISOString().slice(0, 16)); // 设置为当前时间
    $('#deleteBtn').hide();
    $('#problemSection').hide();
    
    $('#inspectionModal').modal('show');
}

// 查看巡检详情
function viewInspection(id) {
    // 获取巡检数据
    $.ajax({
        url: '/security/inspection/' + id,
        type: 'GET',
        success: function(res) {
            if (res.code === 200 && res.data) {
                const inspection = res.data;
                
                // 填充表单
                $('#inspectionId').val(inspection.inspectionId);
                $('#inspectionCode').val(inspection.inspectionCode);
                $('#inspectionArea').val(inspection.inspectionArea);
                $('#inspector').val(inspection.inspector);
                $('#inspectionTime').val(inspection.inspectionTime ? inspection.inspectionTime.slice(0, 16).replace(' ', 'T') : '');
                $('#inspectionType').val(inspection.inspectionType);
                $('#inspectionResult').val(inspection.inspectionResult);
                $('#problemDesc').val(inspection.problemDesc);
                $('#solution').val(inspection.solution);
                $('#status').val(inspection.status);
                $('#remark').val(inspection.remark);
                
                // 显示/隐藏问题部分
                if (inspection.inspectionResult === "1") {
                    $('#problemSection').show();
                } else {
                    $('#problemSection').hide();
                }
                
                // 设置字段为只读
                $('#inspectionForm input, #inspectionForm select, #inspectionForm textarea').prop('disabled', true);
                
                // 设置模态框标题和显示
                $('#inspectionModalLabel').text('查看巡检详情');
                $('#deleteBtn').hide();
                
                // 隐藏保存按钮，修改关闭按钮文本
                $('.modal-footer .btn-primary').hide();
                $('.modal-footer .btn-secondary').text('关闭');
                
                $('#inspectionModal').modal('show');
            } else {
                alert('获取巡检信息失败: ' + (res.msg || '未知错误'));
            }
        },
        error: function(xhr) {
            alert('获取巡检信息错误: ' + xhr.statusText);
        }
    });
}

// 编辑巡检
function editInspection(id) {
    editingId = id;
    
    // 重置表单状态
    $('#inspectionForm')[0].reset();
    $('#inspectionForm input, #inspectionForm select, #inspectionForm textarea').prop('disabled', false);
    $('.modal-footer .btn-primary').show().text('保存');
    $('.modal-footer .btn-secondary').text('取消');
    
    // 获取巡检数据
    $.ajax({
        url: '/security/inspection/' + id,
        type: 'GET',
        success: function(res) {
            if (res.code === 200 && res.data) {
                const inspection = res.data;
                
                // 填充表单
                $('#inspectionId').val(inspection.inspectionId);
                $('#inspectionCode').val(inspection.inspectionCode);
                $('#inspectionArea').val(inspection.inspectionArea);
                $('#inspector').val(inspection.inspector);
                $('#inspectionTime').val(inspection.inspectionTime ? inspection.inspectionTime.slice(0, 16).replace(' ', 'T') : '');
                $('#inspectionType').val(inspection.inspectionType);
                $('#inspectionResult').val(inspection.inspectionResult);
                $('#problemDesc').val(inspection.problemDesc);
                $('#solution').val(inspection.solution);
                $('#status').val(inspection.status);
                $('#remark').val(inspection.remark);
                
                // 显示/隐藏问题部分
                if (inspection.inspectionResult === "1") {
                    $('#problemSection').show();
                } else {
                    $('#problemSection').hide();
                }
                
                // 设置模态框标题和显示
                $('#inspectionModalLabel').text('编辑巡检');
                $('#deleteBtn').show();
                $('#inspectionModal').modal('show');
            } else {
                alert('获取巡检信息失败: ' + (res.msg || '未知错误'));
            }
        },
        error: function(xhr) {
            alert('获取巡检信息错误: ' + xhr.statusText);
        }
    });
}

// 保存巡检信息
function saveInspection() {
    // 表单验证
    if (!$('#inspectionForm')[0].checkValidity()) {
        $('#inspectionForm')[0].reportValidity();
        return;
    }
    
    // 收集表单数据
    const formData = {
        inspectionId: $('#inspectionId').val(),
        inspectionCode: $('#inspectionCode').val(),
        inspectionArea: $('#inspectionArea').val(),
        inspector: $('#inspector').val(),
        inspectionTime: $('#inspectionTime').val().replace('T', ' '),
        inspectionType: $('#inspectionType').val(),
        inspectionResult: $('#inspectionResult').val(),
        problemDesc: $('#problemDesc').val(),
        solution: $('#solution').val(),
        status: $('#status').val(),
        remark: $('#remark').val()
    };
    
    // 确定是新增还是更新
    const isNew = !formData.inspectionId;
    const url = '/security/inspection';
    const method = isNew ? 'POST' : 'PUT';
    
    // 发送请求
    $.ajax({
        url: url,
        type: method,
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function(res) {
            if (res.code === 200) {
                $('#inspectionModal').modal('hide');
                inspectionTable.ajax.reload();
                loadStats();
                alert(isNew ? '新增巡检成功！' : '更新巡检成功！');
            } else {
                alert(isNew ? '新增巡检失败: ' : '更新巡检失败: ' + (res.msg || '未知错误'));
            }
        },
        error: function(xhr) {
            alert(isNew ? '新增巡检错误: ' : '更新巡检错误: ' + xhr.statusText);
        }
    });
}

// 显示删除确认对话框
function showDeleteModal(id) {
    editingId = id;
    $('#deleteModal').modal('show');
}

// 从编辑模态框中删除
function confirmDelete() {
    if (editingId) {
        $('#inspectionModal').modal('hide');
        setTimeout(() => {
            $('#deleteModal').modal('show');
        }, 500);
    }
}

// 删除巡检
function deleteInspection() {
    if (editingId) {
        $.ajax({
            url: '/security/inspection/' + editingId,
            type: 'DELETE',
            success: function(res) {
                $('#deleteModal').modal('hide');
                if (res.code === 200) {
                    inspectionTable.ajax.reload();
                    loadStats();
                    alert('删除巡检成功！');
                } else {
                    alert('删除巡检失败: ' + (res.msg || '未知错误'));
                }
            },
            error: function(xhr) {
                $('#deleteModal').modal('hide');
                alert('删除巡检错误: ' + xhr.statusText);
            }
        });
    }
}

// 搜索巡检
function searchInspection() {
    const params = {
        inspectionCode: $('#searchInspectionCode').val(),
        inspectionArea: $('#searchInspectionArea').val(),
        inspectionType: $('#searchInspectionType').val(),
        inspectionResult: $('#searchResult').val(),
        status: $('#searchStatus').val()
    };
    
    // 重新加载表格数据
    inspectionTable.ajax.url('/security/inspection/list?' + $.param(params)).load();
}

// 重置搜索
function resetSearch() {
    $('#searchForm')[0].reset();
    inspectionTable.ajax.url('/security/inspection/list').load();
}

// 导出巡检数据
function exportInspectionData() {
    const params = {
        inspectionCode: $('#searchInspectionCode').val(),
        inspectionArea: $('#searchInspectionArea').val(),
        inspectionType: $('#searchInspectionType').val(),
        inspectionResult: $('#searchResult').val(),
        status: $('#searchStatus').val()
    };
    
    alert('导出功能待实现');
    // window.location.href = '/security/inspection/export?' + $.param(params);
} 